<template>
    <Teleport to="body">
        <div id="plant-area-container">
            <div id="marker-editor"></div>
            <div class="button-list">
                <button @click="createItem">新增</button>
                <button @click="handleSave">保存</button>
                <button @click="handleClose">关闭</button>
            </div>
        </div>
    </Teleport>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import Markjs from '@wanglin1994/markjs'
import scalePlugin from '@wanglin1994/markjs/src/plugins/scale';
import shapePlugin from '@wanglin1994/markjs/src/plugins/shape';
Markjs.use(scalePlugin)
Markjs.use(shapePlugin)

const emit = defineEmits<{
    (e: 'close'): void;
    (e: 'save', modifiedRawDatas: Array<Editor.CropPlotRawData>): void;
}>()
const props = defineProps<{
    originX: number;
    originY: number;
    originZ: number;
    preloadRawDatas: Array<Editor.CropPlotRawData>;
}>()

// 按origin的比例重置marker-editor的宽高
const setMarkerEditorSize = () => {
    const markerEditor = document.getElementById('marker-editor')
    if (props.originX > props.originZ) {
        markerEditor.style.width = '80%'
    } else {
        markerEditor.style.height = '90%'
    }
    markerEditor.style.aspectRatio = `${props.originX / props.originZ}`
}

const renderPreloadCropPlotDatas = () => {
    if (Array.isArray(props.preloadRawDatas)) {
        props.preloadRawDatas.forEach((cropPlotRawData) => {
            const { pointArr, data } = cropPlotRawData
            const { width, height } = markerEditor.canvasEleRectInfo
            const convertPointArr = pointArr.map((point) => {
                return {
                    x: point.x * width,
                    y: point.y * height
                }
            })
            markerEditor.createShapeMarkItem('rectangle', {
                pointArr: convertPointArr,
                data
            })
        })
    }
}

const handleClose = () => {
    emit('close')
}

const handleSave = () => {
    /**
     * 没有多边形时该方法返回空数组
     */
    const rawDatas: Array<Editor.CropPlotRawData> = markerEditor.getMarkData()
    /** @type {Array<Editor.CropPlotRawData>}  */
    const modifiedRawDatas: Array<Editor.CropPlotRawData> = []
    if (Array.isArray(rawDatas)) {

        let cacheCheckMap = new Map()
        props.preloadRawDatas.forEach((preloadRawData) => {
            const { data, pointArr } = preloadRawData
            const { id } = data
            cacheCheckMap.set(id, pointArr)
        })

        rawDatas.forEach((rawData) => {
            const { data } = rawData
            const { id } = data
            if (modifiedItemIds.has(id)) {
                // 对于已存在的多边形,检查其点是否发生变化
                if (cacheCheckMap.has(id)) {
                    const cachePointArr = cacheCheckMap.get(id)
                    if (JSON.stringify(cachePointArr) !== JSON.stringify(rawData.pointArr)) {
                        modifiedRawDatas.push(rawData)
                    }
                } else {
                    // 对于新增的多边形,直接添加
                    modifiedRawDatas.push(rawData)
                }
            }
        })
        // 释放map
        cacheCheckMap.clear()
        cacheCheckMap = null
    }
    emit('save', modifiedRawDatas)
}


const modifiedItemIds = new Set()

/**
 * @type {Markjs | null}
 */
let markerEditor = null

const defaultOptions = {
    el: null,
    hoverActive: false,
    dbClickActive: true,
    // noCrossing: true,        // 特定形状编辑时，禁用
    // enableAddPoint: true,    // 特定形状编辑时，禁用
    area: true,
    showPen: false,
    singleClickComplete: false,
    pointType: 'circle',
    pointWidth: 2,
    pointStyle: {
        lineWidth: 2,
        strokeColor: '#0088FF',
        fillColor: '#fff'
    },
    lineType: 'borderLine',
    strokeStyle: {
        lineWidth: 5,
        strokeColor: 'rgba(255, 255, 255, 0.7)',
        frontLineWidth: 3,
        frontStrokeColor: '#2196F3'
    },
    fillColor: 'rgba(86,146,48,0.30)',
    // adsorbent: false,
    dbClickRemovePoint: true,
}
function createItem() {
    markerEditor.createShapeMarkItem('rectangle', {
        /** @type {Editor.MarkJSItemCustomData} */
        data: {
            // 获取当前的时间戳作为id
            id: Date.now(),
        },
    })
}
const curEditMarkItem0 = ref(null)
const isCreateMarking0 = ref(false)
onMounted(() => {
    setMarkerEditorSize()
    defaultOptions.el = document.getElementById('marker-editor')
    markerEditor = new Markjs(defaultOptions)
    markerEditor.on('CURRENT-MARK-ITEM-CHANGE', (item) => {
        curEditMarkItem0.value = item
        if (!item) return;
        const { data } = item
        if (data) {
            const { id } = data
            modifiedItemIds.add(id)
        }
    })
    markerEditor.on('IS-CREATE-MARKING-CHANGE', (state) => {
        isCreateMarking0.value = state
    })
    markerEditor.on('COMPLETE-CREATE-ITEM', (state) => {
        // isCreateMarking0.value = state
    })
    markerEditor.on('PLUGINS_LOADED', () => {
        renderPreloadCropPlotDatas()
    })

})

</script>

<style lang="scss" scoped>
#plant-area-container {
    position: fixed;
    top: 50%;
    left: 50%;
    width: 100vw;
    height: 100vh;
    transform: translate(-50%, -50%);
    z-index: 1000;
    background-color: rgba(0, 0, 0, .5);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 1px solid #ccc;
    padding: 10px;

    #marker-editor {
        background-color: gray;
    }

    .button-list {
        padding-top: 10px;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        gap: 10px;
    }
}
</style>